package junior.util;

import junior.util.io.FileUtils;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.URL;

/**
 * @author bo.wu
 * @CreateDate 2014年8月25日
 */
public class ResourceUtils {
	private final static String CLASSPATH_PREFIX = "classpath:";
	private final static String FILE_PREFIX = "file:";
	
	public static String getResourcePath(String path) {
		String resourcePath = path;
		if (path.startsWith(CLASSPATH_PREFIX)) {
			resourcePath = getClasspath(path.substring(CLASSPATH_PREFIX.length()));
		} else if(path.startsWith(FILE_PREFIX)) {
			resourcePath = getFile(path.substring(FILE_PREFIX.length()));
		} else if(path.matches("([a-zA-Z]:[\\\\\\/]|[\\/]).+")) {
			resourcePath = getFile(path);
		}
		
		return resourcePath;
	}
	
	public static InputStream getInputStream(String path) throws Exception {
        if (path.startsWith(CLASSPATH_PREFIX)) {
            InputStream is = ResourceUtils.class.getClassLoader().getResourceAsStream(path.substring(CLASSPATH_PREFIX.length()));
            if (is == null) {
                is = Thread.currentThread().getContextClassLoader().getResourceAsStream(path.substring(CLASSPATH_PREFIX.length()));
                if (is == null) {
                    is = new FileInputStream(getClasspath(path));
                }
            }
            return is;
        }
		return new FileInputStream(getResourcePath(path));
	}
	
	public static String getClasspath(String path) {
		URL url = ResourceUtils.class.getClassLoader().getResource(path);
		if(url == null) {
			url = ResourceUtils.class.getClassLoader().getResource("");
			return FileUtils.appendSeparatorSuffix(url.getPath())+path;
		}
		return url.getPath();
	}
	
	public static String getFile(String path) {
		return path;
	}
}